/*
 * @Author: yangy
 * @Date: 2023-12-20 11:29:11
 * @LastEditors: yangy
 * @LastEditTime: 2023-12-20 11:40:34
 * @FilePath: /admin_vue3_element_plus/src/utils/useManager.js
 * @Description:
 *
 * Copyright (c) 2023 by 青柠利合科技(北京)有限公司, All Rights Reserved.
 */
import { ref, reactive } from "vue";
import { logout, updatePassword } from "@/api/manager";
import { Eptoast, showModal } from "@/utils/util";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
export function useRePassword() {
  const formDrawerRef = ref(null);
  const formRef = ref(null);
  const router = useRouter();
  const store = useStore();

  const form = reactive({
    oldpassword: "",
    password: "",
    repassword: "",
  });
  // 表单验证
  const rules = {
    oldpassword: [
      {
        required: true,
        message: "旧密码不能为空",
        trigger: "blur",
      },
    ],
    password: [
      {
        required: true,
        message: "新密码不能为空",
        trigger: "blur",
      },
    ],
    repassword: [
      {
        required: true,
        message: "确认密码不能为空",
        trigger: "blur",
      },
    ],
  };
  // 修改密码
  const onSubmit = () => {
    formRef.value.validate((valid) => {
      if (!valid) {
        return false;
      }
    });
    // 提交按钮显示loading
    formDrawerRef.value.showLoading();
    updatePassword(form)
      .then((res) => {
        Eptoast("修改密码成功,请重新登录!");
        store.dispatch("logout");
        router.push("/login");
      })
      .finally(() => {
        // 登录按钮关闭 loading
        formDrawerRef.value.hideLoading();
      });
  };

  const openRePasswordForm = () => formDrawerRef.value.open();

  return { formDrawerRef, form, rules, formRef, onSubmit, openRePasswordForm };
}

export function useLogout() {
  // 退出登录
  const router = useRouter();
  const store = useStore();
  const handleLogout = () => {
    showModal("是否退出登录")
      .then((res) => {
        console.log("退出登录");
        logout().finally(() => {
          Eptoast("退出登录成功");
          store.dispatch("logout");
          //跳转到首页
          router.push("/login");
          //提示退出成功
        });
      })
      .catch((res) => {
        console.log("取消");
      });
  };

  return { handleLogout };
}
